import React from 'react';
import { Col, Form, Button, Modal, Tabs } from 'antd';
const R = require('ramda');
import TradeInfo from '../components/TradeInfo';
import DeclareInfo from '../components/DeclareInfo';
import ProductInfo from '../components/ProductInfo';
import DocumentaryInfo from '../components/DocumentaryInfo';
import Clearance from '../components/Clearance';
import Cost from '../components/Cost';
import ImportCD from '../components/ImportCD';
import { message } from "antd";
import Constants from "../../../utils/Constants";
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
export default class OrderDetail extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            searchConditions: {},
            open: false,
            disabled: true,
            costDisabled: true,
            letterDisabled: true,
            attachmentDisabled: true,
            tabActiveKey: "1",
            saveLoading: false, //保存订单的等待模型
            submitLoading: false, //提交订单的等待模型
            errorMsg: "",
            providerId: "", //商品供应商id
        };
    }

    handleOpen = (disabled, letterDisabled, costDisabled, attachmentDisabled, searchConditions, tabActiveKey, providerId) => {
        this.setState({
            open: true,
            disabled: disabled,
            letterDisabled: letterDisabled,
            costDisabled: costDisabled,
            searchConditions: searchConditions,
            attachmentDisabled: attachmentDisabled,
            tabActiveKey: tabActiveKey,
            providerId: providerId
        });
    }

    handleResetFields = (keepArray) => {
        if (R.isNil(keepArray)) keepArray = [];
        if (this.tradeInfo && !R.contains("1")(keepArray)) this.tradeInfo.handleResetFields();
        if (this.declareInfo && !R.contains("2")(keepArray)) this.declareInfo.handleResetFields();
        if (this.productInfo && !R.contains("3")(keepArray)) this.productInfo.handleResetFields();
        if (this.documentaryInfo && !R.contains("4")(keepArray)) this.documentaryInfo.handleResetFields();
        if (this.confirmLetter && !R.contains("5")(keepArray)) this.confirmLetter.handleResetFields();
        if (this.cost && !R.contains("6")(keepArray)) this.cost.handleResetFields();
        if (this.clearance && !R.contains("7")(keepArray)) this.clearance.handleResetFields();
        if (this.importCD && !R.contains("8")(keepArray)) this.importCD.handleResetFields();
    }

    handleCollectForm = () => {
        let dataSource = R.isNil(this.props.orderDataSource) ? {} : this.props.orderDataSource;
        let form = this.tradeInfo.handleCollectForm();
        form = R.merge(form, this.declareInfo.handleCollectForm());
        form = R.merge(form, this.productInfo.handleCollectForm());
        form = R.merge(form, this.documentaryInfo.handleCollectForm());
        form = R.clone(form);
        form.status = R.isNil(dataSource.status) ? "1" : dataSource.status//默认保存草稿，除了草稿还有补充补充资料可以保存
        form.id = R.isEmpty(dataSource) ? "" : dataSource.id;
        form.kindpackage = form.kindpackage ? form.kindpackage.join('|') : undefined;
        return form;
    }

    handleSaveOrder = () => {
        if (this.documentaryInfo.checkDocumentaryInfo()) {
            let form = this.handleCollectForm();
            this.setState({ saveLoading: true });
            form.providerId = this.state.providerId;
            if (R.isNil(form.id) || R.isEmpty(form.id)) {
                this.props.dispatch({
                    type: 'orderManage/createOrder',
                    payload: {
                        dataSource: form,
                        onSuccess: () => this.saveOrSubmitCB("saveLoading", false),
                        onFail: () => this.setState({ saveLoading: false })
                    }
                });
            } else {
                this.props.dispatch({
                    type: 'orderManage/updateOrder',
                    payload: {
                        dataSource: form,
                        onSuccess: () => this.saveOrSubmitCB("saveLoading", true),
                        onFail: () => this.setState({ saveLoading: false })
                    }
                });
            }
        }
    }

    saveOrSubmitCB = (loading, refreshList) => {
        this.setState({ [loading]: false });//去掉loading状态
        if (refreshList) {
            this.props.dispatch({//根据原来的搜索条件刷新数据列表
                type: 'orderManage/queryOrderManageList',
                payload: this.state.searchConditions
            })
            this.handleCancel(["1", "2", "3", "4"]);//还原其他tab页面的数据
        } else {
            this.handleCancel();//创建订单后马上渲染成空表单
        }
    }

    handleSaveAndSubmit = () => {
        if (this.documentaryInfo.checkDocumentaryInfo()) {
            let form = this.handleCollectForm();
            this.setState({ submitLoading: true });
            if (this.props.customer && this.props.customer.businessType === Constants.NUMBER_TWO) {
                form.status = Constants.NUMBER_FIVE;
            } else {
                form.status = Constants.NUMBER_TWO;
            }
            form.providerId = this.state.providerId;
            if (R.isNil(form.id) || R.isEmpty(form.id)) {
                this.props.dispatch({
                    type: 'orderManage/createOrder',
                    payload: {
                        dataSource: form,
                        onSuccess: () => this.saveOrSubmitCB("submitLoading", false),
                        onFail: () => this.setState({ submitLoading: false })
                    }
                });
            } else {
                this.props.dispatch({
                    type: 'orderManage/updateOrder',
                    payload: {
                        dataSource: form,
                        onSuccess: () => this.saveOrSubmitCB("saveLoading", true),
                        onFail: () => this.setState({ submitLoading: false })
                    }
                });
            }
        }
    }

    handleCancel = (keeyArray) => {
        this.handleResetFields(keeyArray);
        this.setState({ tabActiveKey: "1", open: false, searchConditions: {} });
        this.props.dispatch({
            type: "orderManage/refreshState",
            payload: {
                orderDataSource: {},
                customer: {},
                goodsAddress: {},
                linkMan: {},
                buyer: {},
                settlement: {},
                tradeCountry: {},
                countryCD: {},
                placeClearance: {},
                orderCharges: {},
                kindPackage: {},
                lesseeInfo: {},
                supervision: {},
                natureExemption: {},
                priceItem: {},
                orderTgApproval:{},
                declaration: {}
            }
        })
    }

    handleChangeTabe = (key) => {
        this.setState({ tabActiveKey: key })
    }

    handleBack = () => {
        this.setState({ tabActiveKey: (parseInt(this.state.tabActiveKey) - 1) + "" });
    }

    handleGetCurrencyType = () => {
        return this.declareInfo.handleGetCurrencyType();
    }

    handleNext = () => {
        if (this.state.tabActiveKey === "1" && this.tradeInfo.checkTradeInfo()) {
            this.setState({ tabActiveKey: (parseInt(this.state.tabActiveKey) + 1) + "" });
        }
        if (this.state.tabActiveKey === "2" && this.declareInfo.checkDeclareInfo()) {
            let declarationstyle = this.tradeInfo.props.form.getFieldValue("declarationstyle");
            if (declarationstyle === "2") {
                this.productInfo.handleChangeDrawerType("1");
                this.productInfo.props.form.setFieldsValue({ drawertype: "1" });
            }
            this.setState({ tabActiveKey: (parseInt(this.state.tabActiveKey) + 1) + "" });
        }
        if (this.state.tabActiveKey === "3" && this.productInfo.checkProductInfo()) {
            this.setState({ tabActiveKey: (parseInt(this.state.tabActiveKey) + 1) + "" });
        }
    };

    render() {
        let footer = [
            <Button key="back" size="large" disabled={this.state.disabled || this.state.submitLoading || this.state.saveLoading} onClick={this.handleBack.bind(this)} style={{ display: this.state.tabActiveKey === "1" ? "none" : "inline-block" }}>上一步</Button>,
            <Button key="next" size="large" disabled={this.state.disabled} onClick={this.handleNext.bind(this)} style={{ display: this.state.tabActiveKey === "4" ? "none" : "inline-block" }}>下一步</Button>,
            <Button key="save" size="large" loading={this.state.saveLoading} disabled={this.state.disabled || this.state.submitLoading} onClick={this.handleSaveOrder.bind(this)} style={{ display: this.state.tabActiveKey === "4" ? "inline-block" : "none" }}>保存草稿</Button>,
            <Button key="submit" size="large" loading={this.state.submitLoading} disabled={this.state.disabled || this.state.saveLoading} onClick={this.handleSaveAndSubmit.bind(this)} style={{ display: this.state.tabActiveKey === "4" ? "inline-block" : "none" }}>提交审核</Button>,
            <Button key="cancel" size="large" disabled={this.state.disabled || this.state.submitLoading || this.state.saveLoading} onClick={this.handleCancel.bind(this)}>取消</Button>
        ]

        let dataSource = R.isNil(this.props.orderDataSource) ? {} : this.props.orderDataSource;
        dataSource.cstid = R.isNil(this.props.cstid) ? dataSource.cstid : this.props.cstid;
        
        let cost = ""
        if (this.state.disabled) { //编辑订单的时候不允许同时改变费用
            cost = <TabPane tab="费用管理" key="6">{<Cost wrappedComponentRef={(inst) => this.cost = inst} disabled={this.state.costDisabled} dataSource={dataSource} costList={this.props.costList} costPage={this.props.costPage} customer={this.props.customer} dispatch={this.props.dispatch} searchConditions={this.state.searchConditions} handleCancel={this.handleCancel} customs={this.props.customs} type="1" />}</TabPane>
        }

        let widths = { "1": 850, "2": 800, "3": 1000, "4": 860, "5": 1000, "6": 880, "7": 850, "8": 1400 };

        let title = <span>订单详情</span>;
        if (dataSource.status === "3") {
            title = <span style={{ color: 'red' }}>订单详情(通关退回原因: {dataSource.gobackreason})</span>
        }

        let clearance = "";
        if (R.contains(dataSource.status, ["6", "7"])) {
            clearance = <TabPane tab="通关信息" key="7">{<Clearance wrappedComponentRef={(inst) => this.clearance = inst} disabled={true} dataSource={this.props.orderDataSource} orderTgApproval={this.props.orderTgApproval} tgManagerList={this.props.tgManagerList} dispatch={this.props.dispatch} handleCancel={this.handleCancel} customer={this.props.customer} />}</TabPane>
        }

        let importCD = "";
        if (R.contains(dataSource.status, ["5"])) {
            importCD = <TabPane tab="报关单" key="8">{<ImportCD wrappedComponentRef={(inst) => this.importCD = inst} disabled={false} dataSource={this.props.orderDataSource} dispatch={this.props.dispatch} searchConditions={this.state.searchConditions} drawerList={this.props.drawerList}
                customer={this.props.customer} goodsAddress={this.props.goodsAddress} linkMan={this.props.linkMan} buyer={this.props.buyer} settlement={this.props.settlement} tradeCountry={this.props.tradeCountry} countryCD={this.props.countryCD} placeClearance={this.props.placeClearance} orderCharges={this.props.orderCharges} supplyGoodsList={this.props.supplyGoodsList}
                kindPackage={this.props.kindPackage} supervision={this.props.supervision} natureExemption={this.props.natureExemption} priceItem={this.props.priceItem} orderTgApproval={this.props.orderTgApproval} handleCancel={this.handleCancel} lesseeInfo={this.props.lesseeInfo} declaration={this.props.declaration}
                refreshList={this.props.refreshList}
            />}
            </TabPane>
        }
        let declarationstyle = this.tradeInfo ? this.tradeInfo.props.form.getFieldValue("declarationstyle") : undefined;
        return (
            this.state.open ?
                <Modal maskClosable={false} footer={this.state.disabled ? null : footer} visible={this.state.open} title={title} width={widths[this.state.tabActiveKey]} wrapClassName="vertical-center-modal" onCancel={this.handleCancel.bind(this)}>
                    <Tabs activeKey={this.state.tabActiveKey} tabPosition={'left'} onChange={this.handleChangeTabe.bind(this)} >
                        <TabPane tab="交易信息" key="1" disabled={!this.state.disabled}>{<TradeInfo wrappedComponentRef={(inst) => this.tradeInfo = inst} disabled={this.state.disabled} dataSource={dataSource} buyerList={this.props.buyerList} customer={this.props.customer} outbuyId={this.props.outbuyId} />}</TabPane>
                        <TabPane tab="报关信息" key="2" disabled={!this.state.disabled}>{<DeclareInfo wrappedComponentRef={(inst) => this.declareInfo = inst} disabled={this.state.disabled} dataSource={dataSource} customer={this.props.customer} />}</TabPane>
                        <TabPane forceRender={true} tab="产品信息" key="3" disabled={!this.state.disabled}>{<ProductInfo wrappedComponentRef={(inst) => this.productInfo = inst} customer={this.props.customer} disabled={this.state.disabled} handleGetCurrencyType={this.handleGetCurrencyType} dataSource={dataSource} suppilerList={this.props.suppilerList} productPage={this.props.productPage} allProducts={this.props.allproducts} dispatch={this.props.dispatch} supplyGoodsList={this.props.supplyGoodsList} usdRate={this.props.usdRate} declarationstyle={declarationstyle} providerId={this.state.providerId}/>}</TabPane>
                        <TabPane tab="跟单信息" key="4" disabled={!this.state.disabled}>{<DocumentaryInfo wrappedComponentRef={(inst) => this.documentaryInfo = inst} searchConditions={this.state.searchConditions} handleCancel={this.handleCancel} type="1" disabled={this.state.disabled} attachmentDisabled={this.state.attachmentDisabled} dataSource={dataSource} linkmanList={this.props.linkmanArr} addressList={this.props.addressList} dispatch={this.props.dispatch} providerId={this.state.providerId} />}</TabPane>
                        {cost}
                        {clearance}
                        {importCD}
                    </Tabs>
                </Modal> : null
        );
    }
}